import jwt
import time

class JwtCode:
    def __init__(self, algorithm='HS256'):
        self.algorithm = algorithm # 算法

    # 生成token
    def generate_token(self, secret_key, data, exp=60):
        data['exp'] = int(time.time()) + int(exp)  # 过期时间
        token = jwt.encode(data, secret_key, algorithm=self.algorithm)
        return token
    
    # 解码token
    def decode_token(self, secret_key, token):
        try:
            # 验证，设置 verify_exp=False 来禁用自动过期检查
            data1 = jwt.decode(token, secret_key, algorithms=[self.algorithm], options={'verify_exp': False})
            
            exp = data1.pop('exp')
            if exp >= time.time():
                # 未过期
                return {"code": 0, "message": "token未过期", "data": data1}
            else:
                # 已过期
                return {"code": 1, "message": "token已过期"}
        except Exception as e:
            return {"code": 1, "message": f"token解码失败, {e}"}

if __name__ == "__main__":
    jwt_code = JwtCode()
  
   
